from . import admin_bp
import time
from datetime import datetime, timedelta
from flask import request, jsonify, render_template, current_app, redirect
from flask import url_for, abort, session, g
from info import constants, db, user_login_data
from info.models import User, News, Category
from info.utils.captcha.pic_storage import pic_storage
from info.utils.response_code import RET


# 127.0.0.1:5000/admin/
@admin_bp.route('/', methods=['get', 'post'])
@user_login_data
def admin_index():
    """新闻后台首页"""
    user = g.user

    # 数据字典
    data = {
        "user": user.to_dict() if user else None
    }
    return render_template('admin/index.html', data=data)


# 127.0.0.1:5000/admin/login
@admin_bp.route('/login', methods=['get', 'post'])
def admin_login():
    """管理员登陆接口"""
    if request.method == 'GET':
        return render_template("admin/login.html")
    # post请求 管理员登陆
    """
      1.获取参数
        1.1 username:用户名  password:登陆密码
    2.校验参数
        2.1 非空判断
    3.逻辑处理
        3.1 判断用户名密码是否一致
        3.2 判断密码是否正确
        3.3 判断是否为管理员
        3.4 保存管理员登陆信息,设置session属性
    4.返回结果
    """
    # 1.获取参数
    username = request.form.get('username')
    password = request.form.get('password')
    # 2.1 非空判断
    if not all([username, password]):
        return render_template("admin/login.html", errmsg="参数不足")
    # 3.1 判断用户名是否存在
    try:
        user = User.query.filter_by(mobile=username).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="用户查询异常")
    if not user:
        return render_template("admin/login.html", errmsg="该用户不存在")
    # 3.2 判断密码是否正确
    if not user.check_passowrd(password):
        return render_template("admin/login.html", errmsg="密码错误")
    # 3.3 判断是否为管理员
    if not user.is_admin:
        return render_template("admin/login.html", errmsg="用户权限错误")
    # 3.4 保存管理员登陆信息,设置session属性
    session['user_id'] = user.id
    session['nick_name'] = user.nick_name
    session['mobile'] = user.mobile
    session['is_admin'] = True
    # 登陆成功,跳转到首页
    return redirect(url_for('admin.admin_index'))


# 127.0.0.1:5000/admin/user_count
@admin_bp.route('/user_count')
def user_count():
    """用户统计后端接口"""
    # 1.查询总人数
    total_count = 0
    try:
        total_count = User.query.filter_by(is_admin=False).count()
    except Exception as e:
        current_app.logger.error(e)
    # 2.查询月新增人数
    mon_count = 0
    try:
        now = time.localtime()
        # 每个月的第一天
        mon_begin = '%d-%02d-01' % (now.tm_year, now.tm_mon)
        # strptime: 字符串时间转换成时间格式
        mon_begin_date = datetime.strptime(mon_begin, '%Y-%m-%d')
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)
    # 3.查询日新增人数
    day_count = 0
    try:
        now = time.localtime()
        # 每个月的第一天
        day_begin = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
        # strptime: 字符串时间转换成时间格式
        day_begin_date = datetime.strptime(day_begin, '%Y-%m-%d')
        day_count = User.query.filter(User.is_admin == False, User.create_time >= day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)
    # 4.查询图表信息
    # 获取当天00:00:00时间
    now_date = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')
    # 定义空数组,保存数据
    active_date = []
    active_count = []

    # 依次添加数据再反转
    for i in range(0, 31):
        begin_date = now_date - timedelta(days=i)
        end_date = begin_date + timedelta(days=1)
        active_date.append(begin_date.strftime('%Y-%m-%d'))
        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= begin_date, User.last_login <= end_date).count()
        except Exception as e:
            current_app.logger.error(e)
        active_count.append(count)

    active_date.reverse()
    active_count.reverse()

    # 返回的数据字典
    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_date": active_date,
        "active_count": active_count
    }
    return render_template('admin/user_count.html', data=data)


# 127.0.0.1:5000/admin/user_list
@admin_bp.route("/user_list")
@user_login_data
def user_list():
    """用户列表"""
    """
    1.获取页数
    2.查询用户数据(is_admin != True)
        1.1 对数据进行分页
        1.2 生成对象字典列表
    3.返回数据
    """
    # 0.判断用户是否登陆
    user = g.user
    if not user:
        current_app.logger.error("用户未登录")
        return redirect('/admin/login')
    # 1.获取页数
    p = request.args.get('p', 1)
    # 将字符串类型转化为整形
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    # 2.查询用户数据
    try:
        # 对用户进行分页
        paginate = User.query.filter_by(is_admin=False).order_by(User.last_login.desc()).paginate(p, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        # 获取分页数据
        user_page_list = paginate.items
        # 获取当前页数
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return abort(404)
    user_dict_list = []
    for user in user_page_list:
        user_dict_list.append(user.to_admin_dict())
    # 2.返回数据
    # 数据字典
    data = {
        "users": user_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template('admin/user_list.html', data=data)


# 127.0.0.1:5000/admin/news_review
@admin_bp.route('/news_review')
@user_login_data
def news_review():
    """待审核新闻列表"""
    """
    1.获取页数,搜索关键字
    2.查询新闻数据(默认: status != 0)
        1.1 对数据进行分页
        1.2 生成对象字典列表
    3.返回数据
    """
    # 0.判断用户是否登陆
    user = g.user
    if not user:
        current_app.logger.error("用户未登录")
        return redirect('/admin/login')
    # 1.获取页数
    p = request.args.get('p', 1)
    # 获取查询关键字
    keywords = request.args.get("keywords")
    # 将字符串类型转化为整形
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    # 2.查询用户数据
    # 默认查询条件为审核未通过和未审核的新闻
    filter_list = [News.status != 0]
    if keywords:
        # 查询:关键字包含再新闻中的新闻
        filter_list.append(News.title.contains(keywords))

    try:
        # 对用户进行分页
        paginate = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(p,constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        # 获取分页数据
        news_page_list = paginate.items
        # 获取当前页数
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return abort(404)
    news_dict_list = []
    for user in news_page_list:
        news_dict_list.append(user.to_review_dict())

    # 2.返回数据: 返回数据字典
    data = {
        "news_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("admin/news_review.html", data=data)


# 127.0.0.1:5000/admin/news_review_detail
@admin_bp.route("/news_review_detail", methods=['GET', 'POST'])
def news_review_detail():
    """新闻审核详情"""
    """
    GET请求:
        1.获取新闻id
        2.校验新闻id值是否存在
        3.根据新闻id查询新闻数据
        4.将新闻数据返回给前端
    """
    if request.method == 'GET':
        news_id = request.args.get('news_id')
        if not news_id:
            return abort(404)
        try:
            news = News.query.filter(News.id == news_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return abort(404)
        data = {
            "news": news.to_dict()
        }
        return render_template("admin/news_review_detail.html", data=data)
    """
    POST请求:
    1.获取news_id和要执行的操作action
    2.非空判断
    3.逻辑处理
        3.1 根据id查询对应新闻
        3.2 判断操作,改变status状态(拒绝要获取reason参数)
        3.3 保存相应参数到数据库
    4.返回结果
    """
    # 1.获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    # 2.非空判断
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if action not in ['accept', 'reject']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    # 3.1 根据id查询对应新闻
    try:
        news = News.query.filter(News.id == news_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻数据查询异常")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="该新闻不存在")
    # 3.2 判断操作,改变status状态(拒绝要获取reason参数)
    if action == "accept":
        news.status = 0
    else:
        reason = request.json.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="请填写未通过原因")
        news.status = -1
        news.reason = reason
    # 3.3 保存相应参数到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存新闻数据异常")
    # 4.返回结果
    return jsonify(errno=RET.OK, errmsg="操作成功")


# 127.0.0.1:5000/admin/news_edit
@admin_bp.route('/news_edit')
def news_edit():
    """返回新闻列表"""
    """
    1.获取页数,搜索关键字
    2.查询新闻数据
        1.1 对数据进行分页
        1.2 生成对象字典列表
    3.返回数据
    """
    # 1.获取页数
    p = request.args.get('p', 1)
    # 获取查询关键字
    keywords = request.args.get("keywords")
    # 将字符串类型转化为整形
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    # 2.查询用户数据
    # 设置查询条件
    filter_list = []
    if keywords:
        # 查询:关键字包含再新闻中的新闻
        filter_list.append(News.title.contains(keywords))

    try:
        # 对用户进行分页
        paginate = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(p, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        # 获取分页数据
        news_page_list = paginate.items
        # 获取当前页数
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return abort(404)
    news_dict_list = []
    for user in news_page_list:
        news_dict_list.append(user.to_review_dict())

    # 2.返回数据: 返回数据字典
    data = {
        "news_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("admin/news_edit.html", data=data)


# 127.0.0.1:5000/admin/news_edit_detail
@admin_bp.route('/news_edit_detail', methods=['GET', 'POST'])
def news_edit_detail():
    """新闻编辑详情"""
    """
    GET请求:
      1.获取新闻id
      2.校验新闻id值是否存在
      3.根据新闻id查询新闻数据
      4.将新闻数据返回给前端
    """
    if request.method == 'GET':
        news_id = request.args.get('news_id')
        if not news_id:
            return abort(404)
        # 查询新闻数据
        try:
            news = News.query.filter(News.id == news_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return abort(404)
        # 查询新闻分类
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="分类数据查询异常")
        category_list = []
        for category in categories:
            category = category.to_dict()
            # 默认都设置为未被选择状态
            category["is_selected"] = False
            if category["id"] == news.category_id:
                category["is_selected"] = True
            category_list.append(category)
        # 移除`最新`分类
        category_list.pop(0)
        data = {
            "news": news.to_dict(),
            "categories": category_list
        }
        return render_template("admin/news_edit_detail.html", data=data)
    """
    POST请求:
    1.获取参数
        title:新闻标题    category_id:分类id  digest:摘要
        index_image:图片(非必传)  content:新闻内容    news_id:新闻id
    2.非空判断
    3.逻辑处理
       3.1 根据id查询对应新闻
       3.2 设置新闻的对应参数
       3.3 保存相应参数到数据库
    4.返回结果
    """
    # 1.获取参数
    # 前端使用ajaxSubmit提交数据是用form表单提交的
    news_id = request.form.get("news_id")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")
    title = request.form.get("title")
    action = request.form.get("action")
    # 2.非空判断
    if not all([news_id, category_id, digest, content, title]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    # 修改了图片,将图片上传到七牛云
    image_name = None
    if index_image:
        try:
            image_name = pic_storage(index_image.read())
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")
    # 3.1 根据id查询对应新闻
    try:
        news = News.query.filter(News.id == news_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻数据查询异常")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="该新闻不存在")
    # 3.2 设置新闻对应参数
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content
    # 上传到七牛云成功,返回图片name
    if image_name:
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    # 3.3 保存相应参数到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存新闻数据异常")
    # 4.返回结果
    return jsonify(errno=RET.OK, errmsg="新闻编辑成功")


# 127.0.0.1:5000/admin/news_category
@admin_bp.route('/news_category')
def news_category():
    """新闻分类列表"""
    # 1.获取所有分类
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询分类数据异常")
    category_dict_list = []
    for category in categories:
        category_dict_list.append(category.to_dict())
    # 移除"最新"分类
    category_dict_list.pop(0)
    # 2.返回数据: 返回数据字典
    data = {
        "categories": category_dict_list,
    }
    return render_template("admin/news_type.html", data=data)


# 127.0.0.1:5000/admin/add_category
@admin_bp.route('/add_category', methods=['POST'])
def add_category():
    """编辑/新增分类"""
    """
    1.获取参数
        1.1 category_id:分类id  name:分类名称
    2.校验参数
        2.1 非空判断
        2.2 分类是否存在
    3.逻辑处理
        3.1 id存在,修改id对应分类的name值
        3.2 id不存在,创建新的分类对象,设置对应参数
        3.3 将数据保存到数据库
    4.返回结果
    """
    # 1.1 category_id:分类id  name:分类名称
    category_id = request.json.get('id')
    name = request.json.get('name')
    # 2.1 非空判断
    if not name:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    # 2.2 分类是否存在
    try:
        category = Category.query.filter(Category.name == name).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="分类数据查询异常")
    if category:
        return jsonify(errno=RET.DATAEXIST, errmsg="分类已存在")
    # 3.1 id存在,修改id对应分类的name值
    if category_id:
        try:
            category = Category.query.filter(Category.id == category_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="分类数据查询异常")
        if not category:
            return jsonify(errno=RET.NODATA, errmsg="分类不存在")
        category.name = name
    # 3.2 id不存在,创建新的分类对象,设置对应参数
    else:
        category = Category()
        category.name = name
        db.session.add(category)
    # 3.3 将数据保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存分类数据异常")
    # 4 返回结果
    return jsonify(errno=RET.OK, errmsg="操作成功")


# 127.0.0.1:5000/admin/login_out
@admin_bp.route('/login_out')
def login_out():
    """管理后台退出接口"""
    """
    1.删除保存到服务器的session信息
    """
    session.pop("user_id", None)
    session.pop("mobile", None)
    session.pop("nick_name", None)
    session.pop("is_admin", None)
    return redirect(url_for("admin.admin_login"))



